﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace bank
{
    public class ATM
    {
        Bank bank;
        Account account = null;

        public event EventHandler<BigMoneyArgs> BigMoneyFetched;

        public ATM(Bank bank)
        {
            this.bank = bank;
        }

        public bool Register(string account, string password)
        {
            return bank.Register(account, password);
        }

        // ATM类的BigMoneyFetched事件处理方法, 转发事件
        private void Account_BigMoneyFetched(object sender, BigMoneyArgs e)
        {
            BigMoneyFetched?.Invoke(this, e);
        }

        public bool login(string account, string password)
        {
            if ((this.account = bank.FindAccount(account, password)) != null)
            {
                // 注册事件处理方法
                this.account.BigMoneyFetched += Account_BigMoneyFetched;

                return true;
            }
            return false;
        }

        public bool SaveMoney(double money)
        {
            if (account == null) return false;
            try
            {
                return account.SaveMoney(money);
            }
            catch (BadCashException ex)
            {
                // 处理坏钞票异常
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }

        public bool WithdrawMoney(double money)
        {
            if (account == null) return false;
            return account.WithdrawMoney(money);
        }

        public double getMoney()
        {
            if (account == null) return -1;
            return account.getMoney();
        }

        public Account getAccount()
        {
            return account;
        }

        public bool logout()
        {
            account = null;
            return true;
        }

        public bool CloseAccount()
        {
            if (account == null) return false;
            if (bank.CloseAccount(account))
            {
                account = null;
                return true;
            }
            return false;
        }

        public bool isCredit()
        {
            return account is CreditAccount;
        }

        public double getCredit()
        {
            if (account is CreditAccount)
            {
                return ((CreditAccount)account).getCredit();
            }
            return -1;
        }
    }
}
